import domMessage from '../apier/messageOnce'
// eslint-disable-next-line
const messageOnce = new domMessage()

export default {
  params: {
    url: '',
    fileName: '',
    extendParam: '0', // 1显示下载悬浮 0不显示
    localHandle: 'y'
  },

  paramsHandler (params) {
    try {
      let tempDownLoadFile = JSON.parse(localStorage.getItem('tempDownLoadFile')) || []
      tempDownLoadFile.push({
        name: params.fileName,
        fileType: 'downloading',
        status: 'downloading',
        percentage: 0,
        url: params.url,
        uploadTime: new Date()
      })
      localStorage.setItem('tempDownLoadFile', JSON.stringify(tempDownLoadFile))
    } catch (error) {

    }

    /**
     * 下载文件
     *
     * @param url      文件下载地址，必传
     * @param fileName 文档本地存储名称，必传
     * @param userInfo 拼接md5和recordTag字段，###符号隔开(默认无###符号表示recordTag字段值)。如： abcdefg123###1
     *                  ###号前面是 md5
     *                  ###号后面是 recordTag字段值，0：不显示 1：显示
     * @return 原生调用js接口xblDownloadCallable回传值
     */
    if (this._os === 'android') {
      return [params.url, params.fileName, params.extendParam]
    } else if (this._os === 'ios') {
      return [params]
    }
  },

  callback: {
    name: 'xblDownloadCallable',
    /**
     * 下载回调后的参数处理
     * @param {String} status '0'-下载成功 '1'-下载失败 '2'-下载中 '3'-下载中止
     * @param {String} localPath 本地路径
     * @param {String} url 远程路径，status为'2'时，为下载进度
     * @param {Object} extendParam 额外的其他参数，由调用时传给原生函数，原生函数再原样返回
     */
    handler (option, status, localPath, urlOrProgress, extendParam) {
      console.log('xblDownloadCallable:', status, 'urlOrProgress:', urlOrProgress, 'option:', option)
      console.log('xblDownloadCallable _name:', this._name)
      if (['download', 'print'].includes(this._name)) {
        if (status === '2') {
          if (parseFloat(urlOrProgress) > 0) {
            // window.$ui.msg(`文件下载中(${(urlOrProgress * 100).toFixed(2) + '%'})...`)
            messageOnce.success({
              customClass: 'xpad',
              message: `文件下载中(${(urlOrProgress * 100).toFixed(2) + '%'})...`,
              type: 'success'
            })
          }

          //
          // window.$ui.msg(`文件下载中(${(urlOrProgress * 100).toFixed(2) + '%'})...`)
          // window.$ui.alert({
          //   showConfirmButton: false,
          //   showCancelButton: true,
          //   cancelButtonText: '取消下载',
          //   message: `文件下载中(${(urlOrProgress * 100).toFixed(2) + '%'})...`
          // }).then(() => {
          //   // noop
          // }).catch(() => {
          //   this._native.cancelDownload.send({ url: this.params.url })
          // })

          return this.cancelSymbol
        } else {
          window.$ui.alert.close && window.$ui.alert.close()
        }
      }
      let statusMap = ['success', 'fail', 'downloading', 'abort']
      let downloadStatusMap = ['download-success', 'download-fail', 'downloading', 'download-abort']
      try {
        let tempDownLoadFile = JSON.parse(localStorage.getItem('tempDownLoadFile')) || []
        let tempDownLoadFileNew = tempDownLoadFile.map(tempFile => {
          if (tempFile.name === option.fileName) {
            tempFile.fileType = 'downloading'
            tempFile.percentage = parseFloat(urlOrProgress) > 0 && status === '2' ? (urlOrProgress * 100).toFixed(2) : '100'
            tempFile.status = downloadStatusMap[status]
          }
          return tempFile
        })
        localStorage.setItem('tempDownLoadFile', JSON.stringify(tempDownLoadFileNew))
      } catch (error) {
        console.log('file error:', error)
      }

      return {
        status: statusMap[status],
        localPath,
        urlOrProgress,
        extendParam
      }
    }
  }
}
